﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Coolite.Ext.Web;
using Pap.Web.Utils;
using Pap.Web.Modules.Loan.ViewModel;
using Newtonsoft.Json.Linq;

namespace Pap.Web.Modules.Loan.Views
{
    public partial class ReassignLoans : BaseUserControl<ReassignLoansViewModel>
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Ext.IsAjaxRequest && !Page.IsPostBack)
            {
                storeLoansData.DataSource = this.ViewModel.GetLoansData();
                storeLoansData.DataBind();

                storeResponsibles.DataSource = this.ViewModel.GetAllResponsibles();
                storeResponsibles.DataBind();
            }
        }


        /// <summary>
        /// Handles the Clicked event of the BtnSubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnSubmit_Clicked(object sender, AjaxEventArgs e)
        {
            string jsonString = e.ExtraParams["GridData"];
            JArray jsonArray = JSON.Deserialize(jsonString) as JArray;

            Dictionary<Guid, Guid> LoansData = new Dictionary<Guid, Guid>();
            for (int i = 0; i < jsonArray.Count; i++)
            {
                LoansData.Add(jsonArray[i]["LoanID"].ToString().Trim('"').ToGuid(), jsonArray[i]["ResponsibleID"].ToString().Trim('"').ToGuid());
            }

            this.ViewModel.SubmitLoansForResponsibles(LoansData);
        }

        protected void gridLoansData_Command(object sender,AjaxEventArgs e)
        {
            if(e.ExtraParams["CommandName"] == "ViewLoan")
            {
                var loanId = e.ExtraParams["LoanID"];
                this.RedirectFromThisPage("Loan","CreateLoan", "LoanID=" + loanId);
            }
        }
    }
}